package com.rh.service.impl;

import com.rh.entity.SecurityUser;
import com.rh.entity.User;
import com.rh.service.PermissionService;
import com.rh.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 自定义userDetailsService - 认证用户详情
 */
@Service("userDetailsService")//这里的名称要和SpringSecurity注入的UserDetailsService对象名称一致
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;

    /***
     * 根据账号获取用户信息
     * @param username:
     * @return
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中取出用户信息
        User user = userService.selectByUsername(username);
        // 判断用户是否存在
        if (null == user){
            throw new UsernameNotFoundException("用户名不存在！");
        }
        //设置User对象
        User curUser = new User();
        BeanUtils.copyProperties(user,curUser);
        //根据用户查询权限列表
        List<String> authorities = permissionService.selectPermissionValueByUserId(user.getId());
        //把User放到SecurityUser中
        SecurityUser securityUser = new SecurityUser(curUser);
        //设置权限列表
        securityUser.setPermissionValueList(authorities);
        //返回SecurityUser对象
        return securityUser;
    }
}
